package com.project.nimsen.weixin.bean;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Element;

/**
 * 基础消息类型
 * */
public abstract class BaseMsg {
	private String toUserName;//接收信息方
	private String fromUserName;//发送信息方
	private Date createTime;//消息创建时间
	private String msgType;//消息类型
	public String getToUserName() {
		return toUserName;
	}
	public void setToUserName(String toUserName) {
		this.toUserName = toUserName;
	}
	public String getFromUserName() {
		return fromUserName;
	}
	public void setFromUserName(String fromUserName) {
		this.fromUserName = fromUserName;
	}
	public String getCreateTime() {
		return createTime.getTime()+"";
	}
	public void setCreateTime(String createTime) throws ParseException {
		Date date = new Date();
		date.setTime(Long.parseLong(createTime));
		this.createTime = date;
	}
	public String getMsgType() {
		return msgType;
	}
	public void setMsgType(String msgType) {
		this.msgType = msgType;
	}
	
	protected abstract String info();
	/**
	 * 填充子节点信息
	 * @param root 根节点
	 * */
	protected abstract void fullchildProperty(Element root);
	/**
	 * 根据顶节点信息把信息类的属性全部填充
	 * @param root 根节点
	 * @throws ParseException 
	 * */
	public void fullProperty(Element root) throws ParseException{
		
	    String userName = root.elementText("ToUserName");
	    if(StringUtils.isNotBlank(userName))
	    	this.setToUserName(userName);
	    String romUserName = root.elementText("FromUserName");
	    if(StringUtils.isNotBlank(romUserName))
	    	this.setFromUserName(romUserName);
	    String reateTime = root.elementText("CreateTime");
	    if(StringUtils.isNotBlank(reateTime))
	    	this.setCreateTime(reateTime);
		String sgType = root.elementText("MsgType");
		if(StringUtils.isNotBlank(sgType))
			this.setMsgType(sgType);
		
		fullchildProperty(root);
	}
	/**
	 * 直接转换成xml类型
	 * */
	public String convert2xml(){
		StringBuffer xml = new StringBuffer("<xml>");
		
		//toUserName
		xml.append("<ToUserName><![CDATA[").append(this.getToUserName()).append("]]></ToUserName>");
		//fromUserName
		xml.append("<FromUserName><![CDATA[").append(this.getFromUserName()).append("]]></FromUserName>");
		//createTime
		xml.append("<CreateTime>").append(this.getCreateTime()).append("</CreateTime>");
		//msgType
		xml.append("<MsgType>").append(this.getMsgType()).append("</MsgType>");
		//info信息
		xml.append(info());
		
		xml.append("</xml>");
		return xml.toString();
	}
}
